<template>
  <!-- 遮罩层对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="95%" :close-on-click-modal="false"
    :close-on-press-escape="true" :show-close="true" @close="handleClose" class="dicom-viewer-dialog">
    <div class="dicom-viewer-page">
      <div class="page-header">
        <div class="header-controls">
          <el-input v-model="studyInstanceUid" placeholder="请输入检查实例UID" style="width: 300px; margin-right: 10px;"
            disabled />
          <el-select v-model="seriesInstanceUid" placeholder="请选择序列实例" style="width: 300px; margin-right: 10px;">
            <el-option v-for="series in seriesInstanceUidOptions" :key="series.seriseId"
              :label="series.seriseId" :value="series.seriseId" />
          </el-select>
          <el-button type="primary" @click="loadViewer" :loading="loading">
            加载影像
          </el-button>
        </div>
      </div>

      <div class="viewer-container" v-if="showViewer">
        <DicomViewer :studyId="studyId" :studyInstanceUid="studyInstanceUid" :seriesInstanceUid="seriesInstanceUid" :key="viewerKey" />
      </div>
      

      <div class="placeholder" v-else>
        <el-empty description="请输入检查和序列实例UID来加载DICOM影像">
          <template #image>
            <el-icon size="100">
              <Picture />
            </el-icon>
          </template>
        </el-empty>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Picture } from '@element-plus/icons-vue'
import DicomViewer from './components/DicomViewer.vue'
import { getSeriseAllList } from "@/api/pacs/serise/serise"

// 接收父组件传递的属性
const props = defineProps({
  // 是否显示对话框
  modelValue: {
    type: Boolean,
    default: false
  },
  // 对话框标题
  title: {
    type: String,
    default: 'DICOM 医学影像查看器'
  },
  // 初始检查实例ID
  initialStudyId: {
    type: Number,
    default: null,
  },
  // 初始检查实例UID
  initialStudyUid: {
    type: String,
    default: ''
  }
})

// 定义 emits
const emit = defineEmits(['update:modelValue', 'close'])
const { proxy } = getCurrentInstance()

// 响应式数据
const studyId = ref(props.initialStudyId)
const studyInstanceUid = ref(props.initialStudyUid)
const seriesInstanceUid = ref('')
const seriesInstanceUidOptions = ref([])
const showViewer = ref(false)
const loading = ref(false)
const viewerKey = ref(0)

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => {
    emit('update:modelValue', value)
  }
})

const dialogTitle = computed(() => props.title)


// 显示图像的方法
const loadViewer = async () => {
  if (!studyInstanceUid.value.trim() || !seriesInstanceUid.value.trim()) {
    proxy.$modal.msgWarning('请输入检查实例UID和序列实例UID')
    return
  }

  loading.value = true

  try {
    // 验证输入的UID格式
    if (!isValidUID(studyInstanceUid.value) || !isValidUID(seriesInstanceUid.value)) {
      proxy.$modal.msgError('UID格式不正确，请检查输入')
    }

    // 重新加载查看器
    viewerKey.value++
    showViewer.value = true

    proxy.$modal.msgSuccess('开始加载DICOM影像...')

  } catch (e) {
    console.error('加载查看器失败', e)
    proxy.$modal.msgError('加载失败: ' + e.message)
  } finally {
    loading.value = false
  }
}

// 获取序列列表
const fetchSeries = async () => {
  if (!studyInstanceUid.value.trim()) {
    proxy.$modal.msgWarning('请输入检查实例UID')
    return
  }

  if (!isValidUID(studyInstanceUid.value)) {
    proxy.$modal.msgWarning('检查实例UID格式不正确')
    return
  }

  seriesInstanceUidOptions.value = []
  seriesInstanceUid.value = ''

  try {
    // 调用后端API获取序列列表
    const response = await getSeriseAllList({studyId: studyId.value})
    seriesInstanceUidOptions.value = response.data || []
    console.log("序列下拉框数据",seriesInstanceUidOptions.value)

    if (seriesInstanceUidOptions.value.length === 0) {
      proxy.$modal.msgWarning('该检查下没有找到序列数据')
    } else {
      proxy.$modal.msgSuccess(`找到 ${seriesInstanceUidOptions.value.length} 个序列`)
    }
  } catch (e) {
    console.error('获取序列列表失败', e)
    proxy.$modal.msgError('获取序列列表失败: ' + error.message)
  }
}


// 验证UID格式
const isValidUID = (uid) => {
  // DICOM UID格式验证：数字和点组成，长度不超过64字符
  const uidPattern = /^[0-9.]+$/
  return uidPattern.test(uid) && uid.length <= 64 && uid.length > 0
}

// 关闭处理
const handleClose = () => {
  dialogVisible.value = false
  showViewer.value = false
  emit('close')
}

// 监听props变化，当对话框打开/关闭时执行相应操作
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    // 对话框打开时，重置数据
    studyId.value = props.initialStudyId
    studyInstanceUid.value = props.initialStudyUid
    
    // 自动获取序列数据
    console.log('对话框打开，自动获取序列')
    
    // 延迟一下确保DOM渲染完成
    setTimeout(() => {
      if (studyInstanceUid.value && studyInstanceUid.value.trim() !== '') {
        fetchSeries()
      }
    }, 100)
    // 可以选择自动加载
    // loadViewer()
  } else {
    // 对话框关闭时，清理资源
    showViewer.value = false
  }
})

// 暴露方法给父组件
defineExpose({
  loadViewer,
  setStudyId: (id) => { studyId.value = id },
  setStudyUid: (uid) => { studyInstanceUid.value = uid },
})
</script>

<style scoped>
.dicom-viewer-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.dicom-viewer-page {
  height: 70vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.page-header {
  background: white;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.viewer-container {
  flex: 1;
  overflow: hidden;
}

.placeholder {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  margin: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

:deep(.el-empty__description) {
  color: #909399;
  font-size: 16px;
}
</style>